package com.qms.tubu.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.ViewTreeObserver;

import com.qms.tubu.R;
import com.qms.tubu.fragment.PhotoFragment;

/**
 * Created by Mad on 2015/7/29.
 */
public class MultiPhotoActivity extends BaseActivity implements ViewPager.OnPageChangeListener,ViewTreeObserver.OnGlobalLayoutListener{
    private ViewPager mViewPager;
    private String[] mImages;
    private int mPosition;
    private int mHeight,mWidth;
    public static Intent getInstance(Context context,String[] images,int position)
    {
        Intent intent=new Intent(context,MultiPhotoActivity.class);
        intent.putExtra("images",images);
        intent.putExtra("position",position);
        return intent;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_multi_photo);
        mPosition=getIntent().getIntExtra("position",0);
        mImages=getIntent().getStringArrayExtra("images");
        getSupportActionBar().setTitle((mPosition + 1) + "/" + mImages.length);
        mViewPager= (ViewPager) this.findViewById(R.id.photo_view_pager);
        mViewPager.getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    @Override
    public void onGlobalLayout() {
        mHeight=mViewPager.getMeasuredHeight();
        mWidth=mViewPager.getMeasuredWidth();
        mViewPager.setAdapter(new PhotoFragmentAdapter(getSupportFragmentManager()));
        mViewPager.setCurrentItem(mPosition);
        mViewPager.addOnPageChangeListener(this);
        ViewTreeObserver observer=mViewPager.getViewTreeObserver();
        if (Build.VERSION.SDK_INT<16) {
            observer.removeGlobalOnLayoutListener(this);
        } else {
            observer.removeOnGlobalLayoutListener(this);
        }
    }

    public int getHeight() {
        return mHeight;
    }

    public int getWidth() {
        return mWidth;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        getSupportActionBar().setTitle((position+1)+"/"+mImages.length);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private class PhotoFragmentAdapter extends FragmentPagerAdapter{
        public PhotoFragmentAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int position) {
            return PhotoFragment.getInstance(mImages[position]);
        }
        @Override
        public int getCount() {
            return mImages.length;
        }
    }
}
